<template>
  <div>
    <!-- 目录  -->
    <el-card class="box-card">
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        :inline="true"
        class="formMar"
      >
        <el-row>
          <el-col :span="22">
            <el-form-item label="目录名称">
              <el-input v-model="form.subjectName"> </el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option label="启用" value="shanghai"></el-option>
                <el-option label="禁用" value="beijing"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="clearFn">清除</el-button>
              <el-button type="primary" @click="onSubmit"> 搜索 </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="success" @click="showDialog = true">
                <i class="el-icon-edit"></i>
                新增目录</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-alert type="info" :closable="false" class="incoTitle">
        <i class="el-icon-info" style="font-size: 16px"></i>
        数据一共{{ counts }}条
      </el-alert>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" :index="indexFn" label="序号" sortable="">
        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
        <el-table-column prop="directoryName" label="目录名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template #default="{ row }">
            {{ row.addDate | timefilter('YYYY年MM月DD日') }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量"> </el-table-column>
        <el-table-column prop="state" label="状态" :formatter="formatterFn">
        </el-table-column>
        <el-table-column prop="" label="操作" width="160">
          <template #default="{ row }">
            <el-button
              v-if="row.state === 1"
              type="text"
              @click="stateFn(row.id, 0)"
            >
              禁用
            </el-button>
            <el-button v-else type="text" @click="stateFn(row.id, 1)">
              启用
            </el-button>
            <el-button
              type="text"
              :disabled="row.state === 1 ? true : false"
              @click="editSuj(row.id)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              :disabled="row.state === 1 ? true : false"
              @click="delFn(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="form.pagesize"
        layout=" prev, pager, next, sizes, jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="showTitle"
      :visible="showDialog"
      @close="closeDialog"
      width="30%"
      el-option
    >
      <el-form
        :model="resForm"
        ref="resForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属学科" prop="subjectID">
          <el-select
            v-model="resForm.subjectID"
            placeholder="请选择"
            style="width: 100%; margin-bottom: 20px"
          >
            <el-option
              v-for="(item, index) in list"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input
            v-model="resForm.directoryName"
            placeholder="请输入目录名称"
            style="width: 100%; margin-bottom: 20px"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitFn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  getDirectoryListApi,
  delDirectoryApi,
  getStateApi,
  getDirectoryApi,
  editDirectoryApi,
  addDirectoryApi
} from '@/api/contents'
import { getSubjectsSimpleListApi } from '@/api/subject'
export default {
  data() {
    return {
      form: {
        // directoryName: '',
        // state: 1,
        page: 1,
        pagesize: 10
      },
      tableData: [],
      currentPage: 1,
      counts: 0,
      showDialog: false, // 弹窗
      subForm: {},
      resForm: {
        directoryName: '', // 目录名称
        subjectID: '' // 所属学科id
      },
      rules: {
        directoryName: [
          {
            required: true,
            message: '所属学科不能为空',
            trigger: ['blur', 'change']
          }
        ],
        subjectName: [
          {
            required: true,
            message: '目录名称不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      list: {},
      subjectName: ''
    }
  },
  computed: {
    // 控制标题显示不同名字
    showTitle() {
      return this.resForm.id ? '编辑目录' : '新增目录'
    }
  },
  methods: {
    // 搜索
    async onSubmit() {
      await getDirectoryListApi()
      // await getDirectoryListApi(this.form)
      // console.log(this.form.subjectName)
    },
    // 清除
    clearFn() {},
    // 编辑
    async editSuj(id) {
      this.showDialog = true
      // 数据回显
      const { data } = await getDirectoryApi(id)
      this.list.forEach((element) => {
        if (element.value === data.subjectID) {
          this.subjectName = element.label
        }
      })
      console.log(data)
      this.resForm = data
      this.resForm.subjectName = this.subjectName
      this.resForm.directoryName = data.directoryName
      // this.resForm = data
    },
    // 确认
    async submitFn() {
      // 请求接口编辑
      // 判断添加还是编辑
      if (this.resForm.id) {
        // 有id走编辑接口
        await editDirectoryApi(this.resForm)
      } else {
        // 新增
        if (
          this.resForm.directoryName === '' ||
          this.resForm.subjectID === ''
        ) {
          this.$message.error('目录名称或所属学科不能为空')
          return
        }
        await addDirectoryApi(this.resForm)
      }
      this.getDirectoryList()
      this.closeDialog()
    },
    // 取消
    closeDialog() {
      this.showDialog = false
      this.resForm = {
        directoryName: '', // 目录名称
        subjectName: '', // 所属学科
        subjectID: 0
      }
      //   重置校验
      this.$refs.resForm.resetFields()
    },
    // 删除
    async delFn(id) {
      // 删除要加二次确认
      this.$confirm('此操作将永久删除该目录, 是否继续?', '温馨提示')
        .then(async () => {
          await delDirectoryApi(id)
          if (this.tableData.length === 1 && this.page > 1) {
            this.page--
          }
          // 删除成功后，重新渲染
          this.getDirectoryList()
          this.$message.success('删除成功')
        })
        .catch(() => {
          console.log('点击了取消')
        })
    },
    // 序号换行解决
    indexFn(index) {
      // 每页index是递增
      // console.log(index)
      // 每页的第一条数据的序号 = 1 + 前面页的总条数
      return index + 1 + (this.form.page - 1) * this.form.pagesize
    },
    // 每页条数变化了，会切换每页的条数
    handleSizeChange(val) {
      this.form.pagesize = val //  每页显示条目个数
      // this.form.page = 1
      this.getDirectoryList()
      // console.log(`每页 ${val} 条`)
    },
    // 当前页码变换，改变当前页触发执行
    handleCurrentChange(val) {
      this.form.page = val // 当前页码
      this.getDirectoryList()
      // console.log(`当前页: ${val}`)
    },
    // 列表
    async getDirectoryList() {
      const { data } = await getDirectoryListApi(this.form)
      console.log(data)
      this.tableData = data.items
      this.form.pagesize = data.pagesize
      this.counts = data.counts
      this.form.page = data.page
    },
    // 处理状态是否显示
    formatterFn(row, column, cellValue, index) {
      if (cellValue === 1 || cellValue === '1') {
        return '已开启'
      } else if (cellValue === 0) {
        return '已禁用'
      }
      // console.log(row, column, cellValue, index)
      return cellValue
    },
    // 状态切换
    async stateFn(id, state) {
      await getStateApi(id, state)
      this.getDirectoryList()
    }
  },
  async created() {
    this.getDirectoryList()
    const { data: res } = await getSubjectsSimpleListApi()
    this.list = res
    // this.form.subjectID = res.value
  }
}
</script>
<style scoped lang="scss">
* {
  margin: 0;
}
.box-card {
  padding-right: 15px;
  margin-top: 50px;
  .formMar {
    margin-left: -20px;
  }
  ::v-deep .el-form-item__content {
    width: 220px;
  }
  .incoTitle {
    margin-top: 20px;

    ::v-deep .el-alert__description {
      font-size: 16px;
    }
  }
  .test {
    margin-right: 5px;
    color: #46abee;
  }
}
::v-deep .el-dialog__header {
  background-color: #409eff;

  .el-dialog__title {
    font-size: 20px;
    color: #fff;
  }
}
</style>
